﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {



            int key;
            Console.Write("Enter the number to search for in the array: ");
            key = Convert.ToInt32(Console.ReadLine());
            int len;
            Console.Write("Enter the number of array elements: ");
            len = Convert.ToInt32(Console.ReadLine());
            
            int[] ar = new int[len]; 
            Random rd = new Random ();
            for (int i = 0; i < len; i++)
            {
                ar[i] = rd.Next(1, 20);
                //Console.Write(ar[i] + " ");
            }
            Array.Sort(ar);
            for (int i = 0; i < len; i++)
            {
                //ar[i] = rd.Next(1, 20);
                Console.Write(ar[i] + " ");
            }
            Console.WriteLine();
            //ar = new int[] { 10, 15, 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 30 };

           // key = 40;

            int left = 0;
            int right = ar.Length;
            int mid = 0;
            int count = 0;
            bool found = false;
            while (!(left>= right))
            {
                count++;
                mid = left + (right - left) / 2;

                if (ar[mid] == key)
                {
                    found = true;
                    int nnn = mid;
                    while (nnn >= 0 && ar[nnn] == key)
                    {
                        mid = nnn;
                        nnn--;
                    }

                    break;
                }
                else if (ar[mid] > key)
                {
                    right = mid;
                }
                else
                {
                    left = mid + 1;
                }
            }
                
           if (found == false)
                {
                    Console.WriteLine("Element is not present in the array.");
                    return;
                }



           Console.WriteLine("Serial number:  " + (mid + 1));
        }
    }
}
